package cn.edu.lcu.cs.javaprogramming.gui.notepad;

import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

import static java.awt.event.KeyEvent.*;

/**
 * IDEA UI Designer设计的记事本程序
 *
 * @author ling
 * @date 2022/5/18 0:18
 */
public class MyNotepad {
    private JPanel rootPanel;
    private JMenuBar menuBar;
    private JToolBar toolBar;
    private JTextPane content;
    private JPanel statusBar;
    private JButton fileOpenBtn;
    private JMenu helpMenu;
    private JMenuItem helpAboutMenuItem;
    private JButton fileSaveBtn;
    private JButton fileNewBtn;

    private void initMenuBar() {
        // 设置文件菜单
        // 新建 打开 保存 另存为 退出
        JMenu menuFile = new JMenu("文件(F)");
        // 设置菜单的助记符，即按 Alt+char
        menuFile.setMnemonic(VK_F);
        // 文件--新建
        JMenuItem menuItemFileNew = new JMenuItem("新建(N)");
        // 为菜单项设置助记符
        menuItemFileNew.setMnemonic(VK_N);
        // 为菜单项设置快捷键 Ctrl+N
        menuItemFileNew.setAccelerator(KeyStroke.getKeyStroke(VK_N, InputEvent.CTRL_DOWN_MASK));
        menuItemFileNew.addActionListener((e) -> JOptionPane.showMessageDialog(null, "新建文件"));
        // 文件--打开
        JMenuItem menuItemFileOpen = new JMenuItem("打开(O)");
        menuItemFileOpen.setMnemonic(VK_O);
        menuItemFileOpen.setAccelerator(KeyStroke.getKeyStroke(VK_O, CTRL_DOWN_MASK));
        menuItemFileOpen.addActionListener(new FileOpenActionListener());

        menuFile.add(menuItemFileNew);
        menuFile.add(menuItemFileOpen);

        menuBar.add(menuFile);
    }

    public MyNotepad() {
        initMenuBar();
        fileOpenBtn.addActionListener(new FileOpenActionListener());
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame("MyNotepad");
        frame.setContentPane(new MyNotepad().rootPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private class FileOpenActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                try {
                    List<String> lines = Files.readAllLines(selectedFile.toPath());
                    StringBuilder builder = new StringBuilder();
                    String lineSeperator = System.getProperty("line.separator");
                    lines.forEach(line -> builder.append(line).append(lineSeperator));
                    content.setText(builder.toString());
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}
